import { useState, useRef, ChangeEvent, DragEvent } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import axios from "axios";

interface FileUploadProps {
  knowledgeBaseId: string;
  onSuccess?: (uploadedFiles: UploadedFile[]) => void;
  onError?: (error: string) => void;
}

interface UploadedFile {
  id: string;
  name: string;
  fileType: string;
  fileSize: number;
}

interface UploadProgress {
  [key: string]: {
    progress: number;
    fileName: string;
    status: "uploading" | "success" | "error";
    error?: string;
  };
}

export const FileUpload = ({ knowledgeBaseId, onSuccess, onError }: FileUploadProps) => {
  const [isDragging, setIsDragging] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<UploadProgress>({});
  const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const processFiles = async (files: FileList) => {
    const allowedTypes = [
      "application/pdf",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "text/plain",
      "text/markdown",
    ];

    const validFiles = Array.from(files).filter(file => 
      allowedTypes.includes(file.type) || 
      file.name.endsWith(".md") ||
      file.name.endsWith(".txt") ||
      file.name.endsWith(".pdf") ||
      file.name.endsWith(".docx")
    );

    if (validFiles.length === 0) {
      onError?.("请上传PDF、DOCX、TXT或MD格式的文件");
      return;
    }

    const newUploadProgress = { ...uploadProgress };
    
    // 添加文件到上传进度跟踪中
    validFiles.forEach(file => {
      const fileId = `${file.name}-${Date.now()}`;
      newUploadProgress[fileId] = {
        fileName: file.name,
        progress: 0,
        status: "uploading"
      };
    });
    
    setUploadProgress(newUploadProgress);

    // 依次上传文件
    const uploadedResults: UploadedFile[] = [];
    
    for (const file of validFiles) {
      const fileId = `${file.name}-${Date.now()}`;
      try {
        const formData = new FormData();
        formData.append("file", file);
        
        const response = await axios.post(
          `/api/knowledge-bases/${knowledgeBaseId}/upload`,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data"
            },
            onUploadProgress: (progressEvent) => {
              if (progressEvent.total) {
                const percentCompleted = Math.round(
                  (progressEvent.loaded * 100) / progressEvent.total
                );
                
                setUploadProgress(prev => ({
                  ...prev,
                  [fileId]: {
                    ...prev[fileId],
                    progress: percentCompleted
                  }
                }));
              }
            }
          }
        );
        
        if (response.data && response.data.success) {
          setUploadProgress(prev => ({
            ...prev,
            [fileId]: {
              ...prev[fileId],
              status: "success",
              progress: 100
            }
          }));
          
          uploadedResults.push(response.data.data);
        } else {
          throw new Error(response.data?.error || "上传失败");
        }
      } catch (error) {
        console.error("文件上传错误:", error);
        const errorMessage = error instanceof Error ? error.message : "上传失败";
        
        setUploadProgress(prev => ({
          ...prev,
          [fileId]: {
            ...prev[fileId],
            status: "error",
            error: errorMessage
          }
        }));
        
        onError?.(errorMessage);
      }
    }
    
    if (uploadedResults.length > 0) {
      setUploadedFiles(prev => [...prev, ...uploadedResults]);
      onSuccess?.(uploadedResults);
    }
  };

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      processFiles(e.dataTransfer.files);
    }
  };

  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      processFiles(e.target.files);
    }
  };

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  return (
    <div className="w-full">
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        multiple
        className="hidden"
        accept=".pdf,.docx,.txt,.md"
      />
      
      <div
        className={`w-full border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-colors ${
          isDragging 
            ? "border-blue-500 bg-blue-50 dark:bg-blue-950/20" 
            : "border-gray-300 hover:border-blue-400 dark:border-gray-700 dark:hover:border-blue-700"
        }`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={handleButtonClick}
      >
        <div className="mb-4 mx-auto w-16 h-16 text-gray-400 dark:text-gray-600">
          <svg 
            xmlns="http://www.w3.org/2000/svg" 
            fill="none" 
            viewBox="0 0 24 24" 
            stroke="currentColor" 
            className="w-full h-full"
          >
            <path 
              strokeLinecap="round" 
              strokeLinejoin="round" 
              strokeWidth={2} 
              d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" 
            />
          </svg>
        </div>
        
        <h3 className="text-lg font-medium text-gray-900 dark:text-white">
          拖放文件到此处或点击上传
        </h3>
        <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
          支持PDF、Word、TXT和Markdown文件 (最大50MB)
        </p>
        
        <Button 
          className="mt-4" 
          onClick={(e) => {
            e.stopPropagation();
            handleButtonClick();
          }}
        >
          选择文件
        </Button>
      </div>
      
      {/* 上传进度显示 */}
      {Object.keys(uploadProgress).length > 0 && (
        <div className="mt-6 space-y-4">
          <h4 className="text-sm font-medium text-gray-900 dark:text-white">上传进度</h4>
          
          <div className="space-y-3">
            {Object.entries(uploadProgress).map(([fileId, { fileName, progress, status, error }]) => (
              <Card key={fileId} className="p-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <div className="flex-shrink-0">
                      {status === "uploading" && (
                        <div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
                      )}
                      {status === "success" && (
                        <svg className="w-6 h-6 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                      )}
                      {status === "error" && (
                        <svg className="w-6 h-6 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      )}
                    </div>
                    
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate dark:text-white">
                        {fileName}
                      </p>
                      {error && (
                        <p className="text-xs text-red-500">{error}</p>
                      )}
                    </div>
                  </div>
                  
                  <div className="text-xs text-gray-500 dark:text-gray-400">
                    {status === "uploading" ? `${progress}%` : ""}
                  </div>
                </div>
                
                {status === "uploading" && (
                  <div className="mt-2 w-full bg-gray-200 rounded-full h-1.5 dark:bg-gray-700">
                    <div 
                      className="bg-blue-600 h-1.5 rounded-full transition-all duration-300" 
                      style={{ width: `${progress}%` }}
                    ></div>
                  </div>
                )}
              </Card>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}; 